import { ConfigureService } from '@app/configure';
import { DbService } from '@app/db';
import { JwtVerifyService } from '@app/jwt-verify';
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  @Inject()
  private readonly config:ConfigureService
  @Inject()
  private readonly jwt:JwtVerifyService
  @Inject()
  private readonly db:DbService

  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean> {
    let request = context.switchToHttp().getRequest()

    const route = request.route
    let path:string = route.path

    const white = this.config.get<string[]>('white.admin')
    const routePrefix = this.config.get<string>('apiPrefix.admin')
    if(routePrefix != undefined && routePrefix.length > 0) {
      path = path.substring(routePrefix.length + 1)
    }

    const token = request.headers.authorization
    if(!white.includes(path) && !token) return false
    
    if(token) {
      const jwtConfig = this.config.get('jwt.admin.login')
      const payload = this.jwt.verify(token, {secret : jwtConfig.secret})
      if(!payload) return false

      const userId = (payload.key - jwtConfig.scale) / jwtConfig.scale

      const member = await this.db.member.findOne({id : userId}, ['enable', 'roles', 'super', 'belong', 'tenantId'])
      if(!member || member.enable == false) return false
      if(member.super == false) {

      }else {}


      member.id = userId

      request.belong = member.belong
      request.memberId = request.userId = userId
      request.member = member
      request.isSuper = member.super
    }

    
    request.locale = request.headers.locale
    
    return true;
  }
}
